/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { Stmt, ViewTreeNode } from 'arkanalyzer/lib';
import { ArkClass } from 'arkanalyzer/lib/core/model/ArkClass';
import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger';
import { BaseChecker, BaseMetaData } from '../BaseChecker';
import { Rule, Defects, ClassMatcher, MatcherTypes, MatcherCallback } from '../../Index';
import { ViewTreeTool } from '../../utils/checker/ViewTreeTool';
import { IssueReport } from '../../model/Defects';

const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'AvoidNestedWeightCheck');
const gMetaData: BaseMetaData = {
    severity: 3,
    ruleDocPath: 'docs/avoid-nested-layoutWeight-check.md',
    description: 'Avoid nested layoutWeight'
};
let viewTreeTool: ViewTreeTool = new ViewTreeTool();

export class AvoidNestedLayoutweightCheck implements BaseChecker {
    readonly metaData: BaseMetaData = gMetaData;
    public rule: Rule;
    public defects: Defects[] = [];
    public issues: IssueReport[] = [];

    private clsMatcher: ClassMatcher = {
        matcherType: MatcherTypes.CLASS,
        hasViewTree: true
    };

    public registerMatchers(): MatcherCallback[] {
        const matchClazzCb: MatcherCallback = {
            matcher: this.clsMatcher,
            callback: this.check
        };
        return [matchClazzCb];
    }

    public check = (arkClass: ArkClass): void => {
        let viewTreeRoot = arkClass.getViewTree()?.getRoot();
        if (!viewTreeRoot) {
            return;
        }
        this.traverseViewTree(viewTreeRoot, arkClass);
    };

    private traverseViewTree(viewTreeRoot: ViewTreeNode, arkClass: ArkClass): void {
        if (viewTreeTool.hasTraverse(viewTreeRoot)) {
            return;
        }
        if (viewTreeRoot.name === 'Row' || viewTreeRoot.name === 'Column') {
            let stmt = viewTreeRoot.attributes.get('layoutWeight');
            if (stmt) {
                let parent = viewTreeRoot.parent;
                if (parent && (parent.name === 'Row' || parent.name === 'Column') && parent.attributes.has('layoutWeight')) {
                    this.reportIssue(stmt[0], 'layoutWeight');
                }
            }
        }
        if (viewTreeRoot.children.length > 0) {
            for (let child of viewTreeRoot.children) {
                this.traverseViewTree(child, arkClass);
            }
        }
    }

    private reportIssue(stmt: Stmt, key: string): void {
        const severity = this.rule.alert ?? this.metaData.severity;
        const arkFile = stmt.getCfg().getDeclaringMethod().getDeclaringArkFile();
        if (!arkFile) {
            return;
        }
        const filePath = arkFile.getFilePath();
        const originPosition = stmt.getOperandOriginalPosition(stmt.getDefAndUses().length - 1);
        if (!originPosition) {
            return;
        }
        const lineNum = originPosition.getFirstLine();
        const endColunm = originPosition?.getFirstCol() - 1;
        const startColumn = endColunm - key.length;
        let defects = new Defects(lineNum, startColumn, endColunm, this.metaData.description, severity, this.rule.ruleId,
            filePath, this.metaData.ruleDocPath, true, false, false);
        this.issues.push(new IssueReport(defects, undefined));
    }
}